package br.com.ime.usp.cmep;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.markupartist.android.widget.ActionBar.IntentAction;

import br.com.ime.usp.cmep.BandexUtils.BandexComment;
import br.com.ime.usp.cmep.BandexUtils.BandexStatus;
import br.com.ime.usp.cmep.RatingActivity.BandexCommentListAdapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Comparator;

public class CardapioActivity extends Activity {

	private HashMap<String,BandexStatus> status = new HashMap<String,BandexStatus>();
	private boolean downloading = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cardapio);
		
		// configura actionbar
        final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
        actionBar.setTitle(getString(R.string.cardapio_titulo));
        actionBar.setHomeAction(new HomeAction(this));        
        actionBar.addAction(new RefreshAction(this));
        actionBar.addAction(new BackAction(this));
	    
	    // evento onclick
        ListView lv = (ListView)findViewById(R.id.cardapio_bandexlist);
	    lv.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	        	String bandex = (BandexUtils.getList())[position];
				Intent intent = new Intent(CardapioActivity.this, ReadCardapioActivity.class);
				intent.putExtra("bandex", bandex);
				if(status.get(bandex) != null) {
					intent.putExtra("media", status.get(bandex).getTamanhoDaFila());
					intent.putExtra("desvio", status.get(bandex).getDesvioPadrao());
					intent.putExtra("amostras", status.get(bandex).getNumeroDeAmostras());
					intent.putExtra("erro", status.get(bandex).getMargemDeErro());
					intent.putExtra("confianca", status.get(bandex).getConfianca());
					intent.putExtra("precisao", status.get(bandex).getPrecisao());
				}
				else {
					intent.putExtra("media", -1);
					intent.putExtra("desvio", -1);
					intent.putExtra("amostras", -1);
					intent.putExtra("erro", -1);
					intent.putExtra("confianca", -1);
					intent.putExtra("precisao", -1);
				}
				startActivity(intent);
	        }
	    });
	    
	    // baixa o status dos bandexs
	    download();
	}
	
	// esta baixando os dados da rede?
	public boolean isDownloading() { 
		return downloading;
	}
	
	// baixe os dados da rede
	public void download() {
		// cria lista falsa de bandexs
		ArrayList<String> bandexs = new ArrayList<String>( Arrays.asList( BandexUtils.getList() ) );
	    ListView lv = (ListView)findViewById(R.id.cardapio_bandexlist);
	    lv.setAdapter( new MockBandexStatusListAdapter(this, R.id.cardapio_bandexlist, bandexs) );
	    
	    // baixe as coisas
	    downloading = true;
	    new DownloadStatusTask().execute();
	}
	
	
	
	// fazer uma listinha personalizada...
	// quanto trampo!!!!
	public class BandexStatusListAdapter extends ArrayAdapter<BandexStatus> {
	    private int resource;
	    private ArrayList<BandexStatus> items;

	    public BandexStatusListAdapter(Context context, int resource, ArrayList<BandexStatus> items) {
	        super(context, resource, items);
	        this.resource = resource;
	        this.items = items;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	        View v = convertView;
	        if (v == null) {
	        	LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        	v = vi.inflate(R.layout.cardapio_listitem, null);
	        }
	        
	        BandexStatus item = (BandexStatus) items.get(position);
	        if (item != null) {
	        	TextView bandex = (TextView) v.findViewById(R.id.cardapio_listitem_bandex);
	        	TextView medida = (TextView) v.findViewById(R.id.cardapio_listitem_medida);
	        	ProgressBar fila = (ProgressBar) v.findViewById(R.id.cardapio_listitem_fila);
	        	ProgressBar loading = (ProgressBar) v.findViewById(R.id.cardapio_listitem_loading);
	        	
	        	if(bandex != null)
	        		bandex.setText(item.getBandex());
	        	
	        	if(medida != null) {
	        		int e = (int)Math.round(100.0 * item.getMargemDeErro());
	        		int c = (int)Math.round(100.0 * item.getPrecisao());
	        		medida.setText(
	        				getString(R.string.cardapio_medida)
	        					.replace("{e}", "±" + e + "%")
	        					.replace("{p}", c + "%")
	        		);
	        	}

	        	if(fila != null) {
	        		fila.setVisibility(View.VISIBLE);
	        		fila.setMax(100);
	        		fila.setProgress((int)(item.getTamanhoDaFila() * 100.0));
	        	}
	        	
	        	if(loading != null)
	        		loading.setVisibility(View.INVISIBLE);
	        	
	        	status.put(item.getBandex(), item);
	        }
	        
	        return v;
	    }
	}
	
	// listinha sem o tamanho da fila (so' com a bola de carregando)
	public class MockBandexStatusListAdapter extends ArrayAdapter<String> { // passa a lista de bandexs
	    private int resource;
	    private ArrayList<String> items;

	    public MockBandexStatusListAdapter(Context context, int resource, ArrayList<String> items) {
	        super(context, resource, items);
	        this.resource = resource;
	        this.items = items;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	        View v = convertView;
	        if (v == null) {
	        	LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        	v = vi.inflate(R.layout.cardapio_listitem, null);
	        }
	        
	        String item = (String) items.get(position);
	        if (item != null) {
	        	TextView bandex = (TextView) v.findViewById(R.id.cardapio_listitem_bandex);
	        	TextView medida = (TextView) v.findViewById(R.id.cardapio_listitem_medida);
	        	ProgressBar fila = (ProgressBar) v.findViewById(R.id.cardapio_listitem_fila);
	        	ProgressBar loading = (ProgressBar) v.findViewById(R.id.cardapio_listitem_loading);
	        	
	        	if(bandex != null)
	        		bandex.setText(item);
	        	
	        	if(medida != null)
	        		medida.setText("");

	        	if(fila != null)
	        		fila.setVisibility(View.INVISIBLE);
	        	
	        	if(loading != null)
	        		loading.setVisibility(View.VISIBLE);
	        }
	        
	        return v;
	    }
	}
	
	
	// listinha sem o tamanho da fila e sem a bola de carregando
	public class FailedBandexStatusListAdapter extends ArrayAdapter<String> { // passa a lista de bandexs
	    private int resource;
	    private ArrayList<String> items;

	    public FailedBandexStatusListAdapter(Context context, int resource, ArrayList<String> items) {
	        super(context, resource, items);
	        this.resource = resource;
	        this.items = items;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	        View v = convertView;
	        if (v == null) {
	        	LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        	v = vi.inflate(R.layout.cardapio_listitem, null);
	        }
	        
	        String item = (String) items.get(position);
	        if (item != null) {
	        	TextView bandex = (TextView) v.findViewById(R.id.cardapio_listitem_bandex);
	        	TextView medida = (TextView) v.findViewById(R.id.cardapio_listitem_medida);
	        	ProgressBar fila = (ProgressBar) v.findViewById(R.id.cardapio_listitem_fila);
	        	ProgressBar loading = (ProgressBar) v.findViewById(R.id.cardapio_listitem_loading);
	        	
	        	if(bandex != null)
	        		bandex.setText(item);
	        	
	        	if(medida != null)
	        		medida.setText("");

	        	if(fila != null)
	        		fila.setVisibility(View.INVISIBLE);
	        	
	        	if(loading != null)
	        		loading.setVisibility(View.INVISIBLE);
	        }
	        
	        return v;
	    }
	}
	
	
	
	
	
	
	
	
	
	
	// ----------- AsyncTask ------------
	
	private class DownloadStatusTask extends AsyncTask<Void, Void, ArrayList<BandexStatus> > {
		private String error = "";
		
		/** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
	    protected ArrayList<BandexStatus> doInBackground(Void... foo) {
	    	ArrayList<BandexStatus> data = new ArrayList<BandexStatus>();
	    	
	    	try {
		    	// lista de bandexs
			    String[] bandexList = BandexUtils.getList();
			    
			    // quero o status de tds os bandexs
			    for(String bandex : bandexList)
			    	data.add( new BandexStatus(bandex) );
			    
			    // ae, fechou.
	    	}
	    	catch(Exception e){
	    		error = e.getMessage();
	    	}
			
			// pronto
			return data;
	    }
	    
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    protected void onPostExecute(ArrayList<BandexStatus> result) {
	    	if(error.equals(""))
	    		goBack(result);
	    	else
	    		goBack(error);
	    }
	}
	
	// goBack() e' chamado pela AsyncTask: cria a listinha bonita
	protected void goBack(ArrayList<BandexStatus> data) {
	    ListView lv = (ListView)findViewById(R.id.cardapio_bandexlist);
	    lv.setAdapter( new BandexStatusListAdapter(this, R.id.cardapio_bandexlist, data) );
	    downloading = false;
	}
	
	protected void goBack(String error) {
		Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
	    ListView lv = (ListView)findViewById(R.id.cardapio_bandexlist);
	    lv.setAdapter( new FailedBandexStatusListAdapter(this, R.id.cardapio_bandexlist, new ArrayList<String>( Arrays.asList( BandexUtils.getList() )) ));
	    downloading = false;
	}
	
	
	
	
	// --------- coisas da actionbar ---------------
	
	// volta para a tela anterior
    private class BackAction extends AbstractAction {
    	private Activity act;
        public BackAction(Activity a) {
            super(R.drawable.ic_action_back); act = a;
        }
        public void performAction(View view) {
            act.finish();
        }
    }
    
    // atualiza lista
    private class RefreshAction extends AbstractAction {
    	private CardapioActivity act;
        public RefreshAction(CardapioActivity a) {
            super(R.drawable.ic_action_refresh); act = a;
        }
        public void performAction(View view) {
        	if(!act.isDownloading())
        		act.download();
        }
    }
    
    // volta pra home
    private class HomeAction extends AbstractAction {
    	private Activity act;
        public HomeAction(Activity a) {
            super(R.drawable.ic_launcher); act = a;
        }
        public void performAction(View view) {
        	Intent i = new Intent(act, CMEPActivity.class);
        	act.startActivity(i);
        	act.finish();
        }
    }
}
